package com.junchenrobot.mes.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.util.ArrayList;
import java.util.List;

/**
 * FastJson配置 将jackson替换成FastJson
 *
 * @author SeaWave
 * @date 2022/10/19
 */
@Configuration
public class FastJsonConfiguration {
    
    
    /**
     * 配置FastJson消息转换器 消除默认的Jackson消息转换器 修改成fastjson转换器
     *
     * @return {@link HttpMessageConverters}
     */
    @Bean
    public HttpMessageConverters fastJsonMessageConverters() {
        //创建fastJson消息转换器
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //创建配置类
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //过滤并修改配置返回内容
        fastJsonConfig.setSerializerFeatures(
                //List字段如果为null,输出为[],而非null
                SerializerFeature.WriteNullListAsEmpty,
                //数值字段如果为null,输出为0,而非null
                SerializerFeature.WriteNullNumberAsZero,
                //消除对同一对象循环引用的问题，默认为false
                SerializerFeature.DisableCircularReferenceDetect,
                //Enum输出name()或者original,默认为false
                SerializerFeature.WriteEnumUsingToString,
                //是否输出值为null的字段,默认为false
                SerializerFeature.WriteMapNullValue
        );
        //设置格式化的时间格式
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        //2-1 处理中文乱码问题
        // fastJson 添加MediaType
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        //3、在convert中添加配置信息
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters(fastJsonHttpMessageConverter);
    }
    
    
}
